package org.bigtree.example.common.frame.annotations;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 枚举类检验
 *
 * @author bigTree
 * @since 2025/4/26
 */
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValidate.EnumValidator.class)
public @interface EnumValidate {
    /**
     * 错误提示信息
     */
    String message() default "input enum value is invalid.";

    /**
     * 枚举类
     */
    Class<? extends Enum<?>> enumClass ();

    /**
     * 枚举类中静态校验方法
     */
    String methodName() default "";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};


    class EnumValidator implements ConstraintValidator<EnumValidate, Object> {
        private Class<? extends Enum<?>> enumClass;
        private String methodName;

        @Override
        public void initialize(EnumValidate enumValidate) {
            this.enumClass = enumValidate.enumClass();
            this.methodName = enumValidate.methodName();
        }

        @Override
        public boolean isValid(Object param, ConstraintValidatorContext constraintValidatorContext) {
            if (Objects.isNull(param)) {
                return true;
            }
            // 自定义校验方法
            if (StringUtils.hasText(this.methodName)) {
                Method validMethod = ReflectionUtils.findMethod(enumClass, methodName, param.getClass());
                if (Objects.isNull(validMethod)) {
                    throw new RuntimeException(String.format("Enum validator method: %s not found.", methodName));
                }
                Object res = ReflectionUtils.invokeMethod(validMethod, null, param);
                if (Objects.isNull(res)) {
                    throw new RuntimeException(String.format("Enum validator method: %s valid result is null.", methodName));
                }
                if(!(res instanceof Boolean)) {
                    throw new RuntimeException(String.format("Enum validator method: %s valid not is boolean value.", methodName));
                }
                return (boolean) res;
            }
            // 枚举类型接收参数校验
            Method valuesMethod = ReflectionUtils.findMethod(enumClass, "values");
            Enum<?>[] members = (Enum<?>[])ReflectionUtils.invokeMethod(valuesMethod, null);
            for (Enum<?> member : members) {
                if (Objects.equals(member, param)) {
                    return true;
                }
            }
            return false;
        }
    }

}
